package com.googlecode.simplexer.io.implementation;

import com.googlecode.simplexer.io.*;

/**
 * A string of char sequence.
 * 
 * @author Sam Huang
 */
public class StringCharInputSequence implements CharInputSequence {
	private int column = 0;

	private String buffer;
	
	protected String line;
	
	protected int ln;
	
	protected int lineNumber;

	public StringCharInputSequence(String buffer) {
		ln = 1;
		column = 0;		
		this.buffer = buffer + "\n";
	}

	public void backward(int length) {
		column -= length;
	}

	public String forward(int length) {
		String forward = buffer.substring(column, length);
		column += length;
		return forward;
	}

	public char nextchr() {
		if (column >= line.length()) {
			nextLine();
		}
		return line.charAt(column++);
	}

	public String getLine() {
		return line;
	}

	public void nextLine() {
		char chr;
		StringBuffer line = new StringBuffer();
		
		int i = 0;
		column = 0;
		ln++;
		while((chr = buffer.charAt(i)) != '\n'){
			line.append(chr);
			i++;
		}
		this.line = line.toString();
	}

	public void close() {
		line = null;
		buffer = null;
	}

	public int getColumn() {
		return column;
	}

	public int getLineNumber() {
		return ln;
	}

	public String getName() {
		return buffer;
	}

	public String forwardUntil(char chr) {
		char chrr;
		StringBuffer passed = new StringBuffer();
		
		for(int i = column; ; i++){
			chrr = nextchr();
			passed.append(chrr);
			if(chrr == chr){
				break;
			}
		}
		return passed.toString();
	}

	/* (non-Javadoc)
	 * @see com.googlecode.simplexer.io.CharInputSequence#jumpToColumn(int)
	 */
	public void jumpToColumn(int columnToJump) {
		column = columnToJump;
	}

	public void jumpToLine(int lineToJump) {
		for(int i = 0; i < lineToJump; i++) {
			nextLine();
		}
	}

}
